<?php
namespace app\index\controller;

use app\common\model\Fruit as FruitModel;
use app\common\model\UserWallet as UserWalletModel;

use app\common\component\fruit\FruitService;

class ExchangeSecond extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

    public function index() {
    	$userId = \think\Session::get('user_id');

		$fruitServiceFind = (new FruitService()) -> find($userId);
		$this -> view -> assign('fruitSecondBuy', $fruitServiceFind['data']['fruit']['fruit_second_buy']);

        return $this -> view -> fetch();
    }
	
	public function handleExchange() {
		$post = $this -> request -> post();
		if($this -> validate($post, ['price' => 'require|token']) !== true) {
			echo '<script>window.location.href="/exchange/second";</script>';exit;
		}

		$userId = \think\Session::get('user_id');

		$fruitServiceFind = (new FruitService()) -> find($userId);
		if($post['price'] > $fruitServiceFind['data']['fruit']['fruit_second_buy']) {
			echo '<meta charset="utf-8"><script>alert("你兑换的金币大于您拥有的果子!");window.history.go(-1);</script>';exit;
		}

		$resultCheckPayPassword = (new \app\common\component\user\UserService()) -> checkPayPassword($post['pay_password']);
    	if($resultCheckPayPassword['code'] !== 0) {
    		echo '<meta charset="utf-8"><script>alert("' . $resultCheckPayPassword['message'] . '!");window.history.go(-1);</script>';exit;
    	}

		\think\Db::startTrans();
		try {
			if(!FruitModel::where('user_id', $userId) -> setDec('fruit_second_buy', $post['price'])) {
				throw new \Exception('兑换金币失败, FruitModel setDec!');
			}

			$fruitSecondLogServiceCreate = (new \app\common\component\fruit\FruitSecondLogService()) -> create([
				'user_id' => $userId,
				'type' => 5,
				'active' => 0,
				'price' => $post['price'],
				'create_time' => time(),
				'remark' => '兑换金币'
			]);
			if($fruitSecondLogServiceCreate['code'] != 0) {
				throw new \Exception($fruitSecondLogServiceCreate['message']);
			}

			if(!UserWalletModel::where('user_id', $userId) -> setInc('gold', $post['price'])) {
				throw new \Exception('兑换金币失败, UserWalletModel setInc!');
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '");window.history.go(-1);</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("兑换成功!");window.location.href="/exchange/second";</script>';exit;
	}
}
?>